package com.risetechnology.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.risetechnology.krystalkitchen1.R;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Utils {
	public static boolean checkNullOrEmpty(String str) {
		return str == null || str.trim().equals("");
	}
	public static boolean isNetworkConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null && ni.isConnected()) {
			return true;
		}
		return false;
	}
	
	public static void copy(InputStream from, OutputStream to) throws IOException {
		byte[] buffer = new byte[1024];
		int length;
		while ((length = from.read(buffer)) > 0) {
			to.write(buffer, 0, length);
		}
		to.flush();
		to.close();
		from.close();
	}
	
	public static byte[] drawableToByteArray(Drawable d) {

	    if (d != null) {
	        Bitmap imageBitmap = ((BitmapDrawable) d).getBitmap();
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
	        byte[] byteData = baos.toByteArray();

	        return byteData;
	    } else
	        return null;

	}


	@SuppressWarnings("deprecation")
	public static Drawable byteToDrawable(Resources res, byte[] data) {

	    if (data == null)
	        return null;
	    else
	    	try {
				Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
				return new BitmapDrawable(bmp);
			} catch (Exception e) {
				// TODO: handle exception
			}
	        return res.getDrawable(R.drawable.ic_launcher);
	}
	
}
